package com.ptszyxx.popose.module.main.user.vm;

import android.app.Application;
import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.event.DynamicStatusEvent;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ysg.http.data.entity.user.UserAppEntity;
import com.ysg.utils.YUserUtil;
import com.ysg.enums.ChatCallEnum;
import com.ptszyxx.popose.module.main.gift.vm.GiftAndCallVM;
import com.ysg.binding.command.BindingCommand;
import com.ysg.bus.RxBus;
import com.ysg.bus.RxSubscriptions;
import com.ysg.bus.event.SingleLiveEvent;
import com.ysg.http.BaseResponse;
import com.ysg.http.HttpUtils;
import com.ysg.http.callback.OnSuccessResult;
import com.ysg.http.data.CommonRepository;
import com.ysg.http.data.entity.mine.UserConfigEntity;
import com.ysg.http.data.entity.user.UserAuthEntity;
import com.ysg.http.data.entity.user.UserGuardEntity;
import com.ysg.http.data.entity.user.UserResult;
import com.ysg.http.data.entity.user.VoiceSignatureEntity;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YSPUtils;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class UserDetailVM extends GiftAndCallVM {
    public String userId;
    public ObservableField<UserResult> userEntity = new ObservableField<>();
    public ObservableField<UserGuardEntity> guardEntity = new ObservableField<>();
    public UserConfigEntity userConfig = YSPUtils.getInstance().getUserConfig();

    public UserDetailVM(@NonNull Application application, CommonRepository model) {
        super(application, model);
    }


    //TODO 2.ui通知处理=====================
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        public SingleLiveEvent onBannerEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onVoiceEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onUserAuthEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onFollowEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onOtherEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onUserMineEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onGuardEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onGuardDialogEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onVipEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onBuyEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onBuyedEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onLookDiamondEvent = new SingleLiveEvent<>();
    }

    //TODO 2.点击事件处理=====================
    public BindingCommand onLeftCommand = new BindingCommand(()-> YActivityUtil.getInstance().close(UserDetailVM.this));
    public BindingCommand onRightCommand = new BindingCommand(()-> jumpUserSet());
    public BindingCommand onGuardCommand = new BindingCommand(()-> onGuardClick());
    public BindingCommand onFollowCommand = new BindingCommand(()-> requestFollow());
    public BindingCommand onChatCommand = new BindingCommand(()-> jumpChat());
    public BindingCommand onHeartCommand = new BindingCommand(()-> requestHeart());
    public BindingCommand onLookCommand = new BindingCommand(()-> onLookNumber());
    public BindingCommand onVideoCommand = new BindingCommand(()-> onCall(ChatCallEnum.VIDEO));
    public BindingCommand onAudioCommand = new BindingCommand(()->onCall(ChatCallEnum.AUDIO));
    public BindingCommand onLookDiamondCommand = new BindingCommand(()->requestUserApp());



    //TODO 3.异步通知处理=====================
    public Disposable disposable;
    @Override
    public void registerRxBus() {
        super.registerRxBus();
        disposable = RxBus.getDefault().toObservable(DynamicStatusEvent.class)
                .subscribe(new Consumer<DynamicStatusEvent>() {
                    @Override
                    public void accept(DynamicStatusEvent event){
                        if (event != null){
                            userEntity.get().setNotDongtaiState(event.getStatus());
                        }
                    }
                });
    }

    @Override
    public void removeRxBus() {
        super.removeRxBus();
        RxSubscriptions.remove(disposable);
    }



    //TODO 4.接口处理=====================
    /**
     * 请求用户信息
     */
    public void requestUser(){
        Map<String, String> map = new HashMap<>();
        map.put("userid", userId);

        HttpUtils.getInstance()
                .data(model.userInfo(map), this,
                        new OnSuccessResult<UserResult>() {
                            @Override
                            public void onSuccessResult(BaseResponse<UserResult> response) {
                                UserResult result = response.getData();
                                userEntity.set(result);
                                setBanner(result);
                                setVoice();
                                onUserAuthStatus(result);
                                uc.onFollowEvent.call();
                                uc.onOtherEvent.call();
                                uc.onUserMineEvent.call();
                            }
                        });
    }

    /**
     * 请求用户信息
     */
    public void requestUserApp(){
        Map<String, String> map = new HashMap<>();
        map.put("id", userId);

        HttpUtils.getInstance()
                .data(model.userInfoApp(map), this,
                        new OnSuccessResult<UserAppEntity>() {
                            @Override
                            public void onSuccessResult(BaseResponse<UserAppEntity> response) {
                                uc.onLookDiamondEvent.setValue(response.getData());
                            }
                        });
    }

    /**
     * 请求守护
     */
    public void requestGuard(){
        Map<String, String> map = new HashMap<>();
        map.put("beiUserId", userId);

        HttpUtils.getInstance()
                .data(model.userGuard(map), this,
                        new OnSuccessResult<UserGuardEntity>() {
                            @Override
                            public void onSuccessResult(BaseResponse<UserGuardEntity> response) {
                                if (response.getData() != null){
                                    guardEntity.set(response.getData());
                                    uc.onGuardEvent.call();
                                }
                            }
                        });
    }

    /**
     * status:1为关注 2取消关注
     */
    public void requestFollow(){
        Integer status = 1;
        UserResult data = userEntity.get();
        if (null == data){
            return;
        }
        if (YStringUtil.eq(1, data.getGuanzhuState())) {
            status = 2;
        } else if (YStringUtil.eq(2, data.getGuanzhuState())) {
            status = 1;
        }
        Map<String, String> map = new HashMap<>();
        map.put("userid", userId);
        map.put("leixing", String.valueOf(status));

        Integer finalStatus = status;
        HttpUtils.getInstance()
                .data(model.follow(map), this,
                        new OnSuccessResult() {
                            @Override
                            public void onSuccessResult(BaseResponse response) {
                                YToastUtil.showShort(R.string.success);
                                userEntity.get().setGuanzhuState(finalStatus);
                                uc.onFollowEvent.call();
                            }
                        });
    }

    /**
     * 心动礼物
     */
    public void requestHeart(){
        Map<String, String> map = new HashMap<>();
        map.put("userid", userId);
        HttpUtils.getInstance()
                .data(model.heart(map), this,
                        new OnSuccessResult() {
                            @Override
                            public void onSuccessResult(BaseResponse response) {
                                jumpChat();
                            }
                        });
    }


    /**
     * vip列表
     */
    public void requestVip(){
        if (YUserUtil.isVip()){
            uc.onBuyedEvent.call();
        }else{
            uc.onVipEvent.call();
        }
    }
    /**
     * 购买
     */
    public void requestBuy(){
        if (userConfig == null) return;

        Map<String, String> map = new HashMap<>();
        map.put("userId", userId);
        map.put("diamonds", userConfig.getUserInfoSeePrice());
        HttpUtils.getInstance()
                .data(model.buy(map), this, new OnSuccessResult() {
                    @Override
                    public void onSuccessResult(BaseResponse response) {
                        uc.onBuyedEvent.call();
                    }
                });
    }
    /**
     * 是否购买
     */
    public void requestIsBuy(){
        Map<String, String> map = new HashMap<>();
        map.put("userId", userId);
        HttpUtils.getInstance()
                .data(model.isBuy(map), this, new OnSuccessResult<Boolean>() {
                    @Override
                    public void onSuccessResult(BaseResponse<Boolean> response) {
                        if (response.getData() != null && response.getData()){
                            uc.onBuyedEvent.call();
                        }else{
                            uc.onBuyEvent.call();
                        }
                    }
                });
    }




    //TODO 5.逻辑处理=====================
    /**
     * 查看：手机号，微信号，qq号
     * userSwitch:2.需要开通vip；3.需要钻石购买
     */
    private void onLookNumber() {
        if (userConfig != null && YStringUtil.eq(2, userConfig.getUserSwitch())){
            requestVip();
        }else if (userConfig != null && YStringUtil.eq(3, userConfig.getUserSwitch())){
            requestIsBuy();
        }
    }

    /**
     * 是否为自己
     */
    public boolean isSelf(){
        return YUserUtil.isMe(userId);
    }

    /**
     * 聊天
     */
    public void jumpChat(){
        if (userEntity.get() != null){
            YActivityUtil.getInstance().jumpChat(this, userEntity.get().getTengxuncode()+"", userEntity.get().getNick(), userEntity.get().getPic());
        }
    }
    /**
     * 好友设置
     */
    public void jumpUserSet(){
        if (userEntity.get() != null){
            if (isSelf()){
                YActivityUtil.getInstance().jumpUserEdit(UserDetailVM.this, userId);
            }else {
                YActivityUtil.getInstance().jumpUserSet(UserDetailVM.this, userId, userEntity.get().getNotDongtaiState()+"");
            }
        }
    }

    /**
     * 守护事件
     */
    private void onGuardClick() {
        UserGuardEntity guardEntity = this.guardEntity.get();
        if (guardEntity == null){
            return;
        }
        if (YStringUtil.eq(1, guardEntity.getIsHaveGuard())) {//已经有人守护
            YActivityUtil.getInstance().jumpGuard(this, userId, userEntity.get().getTengxuncode());

        } else {//没人守护
            uc.onGuardDialogEvent.call();
        }
    }

    /**
     * 用户认证状态：手机，实名，真人
     */
    private void onUserAuthStatus(UserResult result) {
        List<UserAuthEntity> list = result.getUserAuthDtoList();
        if (YCollectionUtil.isNotEmpty(list)){
            uc.onUserAuthEvent.setValue(list);
        }
    }

    /**
     * 语音
     */
    private void setVoice(){
        UserResult result = userEntity.get();
        if (result == null){
            return;
        }
        VoiceSignatureEntity signatureDto = result.getSignatureDto();
        if (signatureDto == null){
            return;
        }
        if (YStringUtil.isNotEmpty(signatureDto.getVoiceUrl()) && YStringUtil.eq(2, signatureDto.getStatus())){
            uc.onVoiceEvent.call();
        }
    }

    /**
     * 轮播图数据
     */
    private void setBanner(UserResult result) {
        List<String> bannerList = new ArrayList<>();
        if (YStringUtil.isEmpty(result.getXingxiang())){
            if (YStringUtil.isNotEmpty(result.getPic())){
                bannerList.add(result.getPic());
            }
        }else {
            String[] split = result.getXingxiang().split(",");
            for (int i = 0; i < split.length; i++) {
                bannerList.add(split[i]);
            }
        }

        if (YCollectionUtil.isNotEmpty(bannerList)){
            uc.onBannerEvent.setValue(bannerList);
        }
    }



    //===============================拨打电话：start=============================================
    public void onCall(ChatCallEnum callEnum) {
        if (userEntity.get() != null){
            onCallClick(userEntity.get().getTengxuncode(), callEnum);
        }
    }
    //===============================拨打电话：end=============================================




}
